import {
  Row,
  Col,
  Flex,
  Typography,
  Button,
  Form,
  Input,
  Divider,
  Radio,
  Switch,
  Checkbox,
  Select,
  Modal,
  TreeSelect,
  Transfer,
  message,
  Table
} from 'antd'
import React, { useEffect, useState } from 'react'
import MyDatePicker from '../components/MyDatePicker2'
import ManyUpload from '../components/ManyUpload'
import { useNavigate, useParams } from 'react-router-dom'
import {
  adminActivatyAddAPI,
  adminActivatyEditAPI,
  adminActivatyInfo,
  adminCouponList
} from '../service/activaty'
import { cityTreeAPI, shopList, shopListByCityIdAPI } from '../service/shop'
import { userGroupList } from '../service/user'
import dayjs from 'dayjs'

export default function MarketAddActivaty() {
  // 是否显示提示为空信息
  const [isShow, setIsShow] = useState(false)
  const [isShow2, setIsShow2] = useState(false)
  // 初始化日期
  const [initialDate, setInitialDate] = useState()
  const navigate = useNavigate()
  // 是否开启推送
  const [push, setPush] = useState(false)
  // 用户行为
  const [action, setAction] = useState('LBS')
  // 自动化营销是否开启
  const [checked, setChecked] = useState(false)
  const { id } = useParams() // 获取路由参数中的id
  const isEditing = id !== undefined // 根据id是否存在判断是编辑还是添加
  const [form] = Form.useForm()
  // 新建活动还是编辑活动
  const [title, setTitle] = useState(isEditing ? '编辑活动' : '新建活动')
  // 店铺的id
  const [businessId, setBusinessId] = useState([])
  // 店铺名称列表
  const [businessName, setBusinessName] = useState([])
  // 图片列表
  const [fileList, setFileList] = useState([])
  // 是否打开指定店铺模态框
  const [shopOpen, setShopOpen] = useState(false)
  // 是否打开指定人群模态框
  const [personOpen, setPersonOpen] = useState(false)
  // 人群列表
  const [personList, setPersonList] = useState([])
  // 优惠券模态框
  const [couponOpen, setCouponOpen] = useState(false)
  // 优惠券列表
  const [couponList, setCouponList] = useState([])
  // 是否有选中优惠券
  const [selectedLabel, setSelectedLabel] = useState()
  const [selectedCoupon, setSelectedCoupon] = useState('')
  const [tmpSelectedCoupon, setTmpSelectedCoupon] = useState('')
  // 选中优惠券id
  const [selectedCouponId, setSelectedCouponId] = useState('')
  const [tmpSelectedCouponId, setTmpSelectedCouponId] = useState('')
  // 选择指定区域
  const [region, setRegion] = useState([])
  // 三级省市区数据
  const [regionData, setRegionData] = useState([])
  // 保存选择的日期
  const [selectedDateString, setSelectedDateString] = useState(null)
  // 保存注册的日期范围
  const [registerDate, setRegisterDate] = useState(null)
  // 保存选中的人群
  const [selectedPerson, setSelectedPerson] = useState([])
  // 最终保存的人群
  const [selectedConfirmPerson, setSelectedConfirmPerson] = useState([])

  // 保存选中的人群id
  const [selectedPersonId, setSelectedPersonId] = useState('')
  const [selectedConfirmPersonId, setSelectedConfirmPersonId] = useState('')

  // 穿梭机数据
  const [mockData, setMockData] = useState([])
  const initialTargetKeys = mockData
    .filter((item) => Number(item.key) > 10)
    .map((item) => item.key)
  const [targetKeys, setTargetKeys] = useState(initialTargetKeys)
  // 选中的投放渠道
  const [tf, setTf] = useState([])
  // 投放渠道
  const tfOptions = [
    {
      label: '内容页面',
      value: '内容页面'
    },
    {
      label: '定时推送',
      value: '定时推送'
    },
    {
      label: '即时推送',
      value: '即时推送',
      disabled: !checked
    }
  ]
  // 递归函数处理三级城市树
  function transformData(data) {
    return data.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
        children: item.children ? transformData(item.children) : null
      }
    })
  }

  useEffect(() => {
    // 获取三级城市树
    ;(async () => {
      const res = await cityTreeAPI()
      console.log(res.data)
      const newData = transformData(res.data)
      console.log(newData)
      setRegionData(newData)
    })()
    // 获取优惠券
    ;(async () => {
      const res = await adminCouponList({
        pageNo: 1,
        pageSize: 1000
      })
      console.log(res)
      // 保存优惠券
      setCouponList(res.data.objects)
    })()
    // 获取所有店铺
    // ;(async () => {
    //   const res = await shopList({
    //     pageNo: 1,
    //     pageSize: 1000
    //   })
    //   console.log(res)
    //   const arr = res.data.objects.map((item) => {
    //     return {
    //       key: item.id,
    //       title: item.storeName,
    //       chosen: false
    //     }
    //   })
    //   console.log(arr)
    //   setMockData(arr)
    // })()
    // 获取人群列表
    ;(async () => {
      const res = await userGroupList({ pageNo: 1, pageSize: 1000 })
      console.log(res)
      setPersonList(res.data.objects)
    })()
    if (isEditing) {
      ;(async () => {
        const res = await adminActivatyInfo(id)
        console.log(res)
        // 给表单赋值
        form.setFieldsValue(res.data)
        // 设置主图
        setFileList(
          res.data.imgIds.split(',').map((item, index) => {
            return {
              id: item,
              url: res.data.imgPics[index]
            }
          })
        )
        // 设置初始日期
        setInitialDate([
          dayjs(res.data.startDate, 'YYYY-MM-DD HH:mm:ss').startOf('day'),
          dayjs(res.data.endDate, 'YYYY-MM-DD HH:mm:ss')
            .add(1, 'day')
            .startOf('day')
        ])
        // 设置店铺
        // 判断店铺有几个
        const shop = res.data.shopIds
        if (shop.includes(',')) {
          setBusinessId(shop.split(','))
        } else {
          setBusinessId([shop])
        }
        // 通过店铺id找到对应店铺名称

        // 设置指定人群
        // 判断有多少人群
        if (res.data.targetCustomer.includes(',')) {
          setSelectedConfirmPersonId(res.data.targetCustomer.split(','))
        } else {
          setSelectedConfirmPersonId([res.data.targetCustomer])
        }
        // 判断奖励

        // // 设置奖励
        // setSelectedPersonId(res.data.userGroupIds.split(','))
      })()
    } else {
    }
  }, [])
  return (
    <>
      <Row className="info">
        <Col span={24}>
          <Flex justify={'space-between'}>
            <Typography.Title level={3}>{title}</Typography.Title>
          </Flex>
        </Col>
      </Row>
      <Form
        labelCol={{
          span: 2
        }}
        wrapperCol={{
          span: 12
        }}
        style={{ width: '100%', marginTop: 30 }}
        form={form}
        onFinish={(values) => {
          // 判断指定店铺是否为空
          if (businessId.length === 0) {
            setIsShow(true)
            return
          }
          // 判断活动人群是否为空
          if (selectedConfirmPersonId.length === 0) {
            setIsShow2(true)
            return
          }
          // 获取图片
          const imgIds = fileList.map((item) => {
            if (item.response) {
              return item.response.data.id
            } else {
              return item.id
            }
          })
          values.imgIds = imgIds.join(',')
          values.startDate = selectedDateString[0]
          values.endDate = selectedDateString[1]
          // 添加优惠券id
          values.rewardCouponId = selectedCouponId
          // 选中的人群id，id用逗号隔开啊
          values.targetCustomer = selectedConfirmPersonId.join(',')
          // 选中的店铺id,id之间逗号隔开
          values.shopIds = businessId.join(',')
          // 投放渠道
          // values.deliveryChannel = tf.join(',')
          values.deliveryChannel = 1
          // 自动化营销类型
          values.marketingType = checked ? 1 : 0
          console.log(values)
          // 判断编辑还是添加
          if (isEditing) {
            // 编辑
            ;(async () => {
              const res = await adminActivatyEditAPI({ ...values, id })
              console.log(res)
              if (res.code === '0') {
                message.success('编辑成功')
                navigate('/admin/market/activaty')
              }
            })()
          } else {
            // 添加
            ;(async () => {
              const res = await adminActivatyAddAPI(values)
              console.log(res)
              if (res.code === '0') {
                message.success('添加成功')
                navigate('/admin/market/activaty')
              }
            })()
          }
        }}
      >
        <Row className="container" style={{ marginBottom: 0, marginTop: 0 }}>
          <Col span={24}>
            <Typography.Title level={4}>基本信息</Typography.Title>
          </Col>
          <Col span={24}>
            <Form.Item
              label="活动名称"
              name="activityName"
              rules={[{ required: true, message: '活动不能为空' }]}
            >
              <Input
                style={{ width: 300 }}
                maxLength={30}
                showCount
                placeholder="请输入活动名称"
              />
            </Form.Item>
            <Form.Item label="活动图片">
              <ManyUpload fileList={fileList} setFileList={setFileList} />
            </Form.Item>
            <Form.Item label="活动时间">
              <MyDatePicker
                selectedDateString={selectedDateString}
                setSelectedDateString={setSelectedDateString}
                initialDate={initialDate}
              />
            </Form.Item>
            <Form.Item
              label="活动说明"
              name="describes"
              rules={[{ required: true, message: '活动说明不能为空' }]}
            >
              <Input.TextArea style={{ height: 120, resize: 'none' }} />
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col>
            <Divider style={{ margin: 0 }} />
          </Col>
        </Row>
        <Row className="container" style={{ marginTop: 0, marginBottom: 0 }}>
          <Col span={24}>
            <Typography.Title level={4}>场景设计</Typography.Title>
          </Col>
          <Col span={24}>
            <Form.Item
              label="活动目标"
              name="activityTarget"
              rules={[{ required: true, message: '活动目标不能为空' }]}
            >
              <Input style={{ width: 300 }} placeholder="请输入活动目标" />
            </Form.Item>
            <Form.Item label="适用店铺" hasFeedback required>
              <Button type="primary" onClick={() => setShopOpen(true)}>
                指定店铺
              </Button>
              <span style={{ marginLeft: 10 }}>{businessName.join(',')}</span>
              {isShow && (
                <div className="ant-form-explain">适用店铺不能为空</div>
              )}
            </Form.Item>
            <Form.Item label="活动人群" required>
              <Button type="primary" onClick={() => setPersonOpen(true)}>
                指定人群
              </Button>
              <span style={{ marginLeft: 10 }}>
                {selectedConfirmPerson.join(',')}
              </span>
              {isShow2 && (
                <div className="ant-form-explain">指定人群不能为空</div>
              )}
            </Form.Item>
            <Form.Item label="自动化营销" name="marketingType">
              <Switch
                checked={checked}
                onChange={(v) => {
                  setChecked(!checked)
                  setPush(v)
                  if (v) {
                    // 将即时推送复选框为勾选状态
                    setTf(['即时推送'])
                  }
                }}
              />
            </Form.Item>
            <Form.Item label="投放渠道">
              <>
                <Checkbox>内容页面</Checkbox>
                <Checkbox>定时推送</Checkbox>
                <Checkbox
                  checked={push}
                  onChange={(e) => {
                    setPush(e.target.checked)
                    setChecked(e.target.checked)
                  }}
                >
                  即时推送
                </Checkbox>
              </>
              {/* <Checkbox.Group
                options={tfOptions}
                defaultValue={['即时推送']}
                onChange={(value) => {
                  setTf(value)
                  console.log(value)
                  // 是否含有即时推送
                  // setPush(value.includes('即时推送'))
                  // 如果含有计时推送
                  if (value.includes('即时推送')) {
                    setPush(true)
                    // 设置Switch为选中
                    setChecked(true)
                  } else {
                    setPush(false)
                    setChecked(false)
                  }
                }}
              /> */}
            </Form.Item>
            {checked && push && (
              <Form.Item label="用户行为">
                <Select
                  defaultValue={'LBS'}
                  style={{ width: 300 }}
                  options={[
                    {
                      label: 'LBS',
                      value: 'LBS'
                    },
                    {
                      label: '注册',
                      value: '注册'
                    }
                  ]}
                  onChange={(value) => {
                    setAction(value)
                  }}
                />
              </Form.Item>
            )}
            {checked && push && action === 'LBS' && (
              <Form.Item label="距离门店">
                <Button style={{ backgroundColor: '#EEE' }}>5</Button>
                KM
              </Form.Item>
            )}
            {checked && push && action === '注册' && (
              <>
                <Form.Item label="注册时间">
                  <MyDatePicker
                    selectedDateString={registerDate}
                    setSelectedDateString={setRegisterDate}
                  />
                </Form.Item>
                <Form.Item label="注册渠道" name="registerType">
                  <Select
                    defaultValue={'APP'}
                    style={{ width: 300 }}
                    options={[
                      {
                        label: 'APP',
                        value: 'APP'
                      },
                      {
                        label: '小程序',
                        value: '小程序'
                      }
                    ]}
                  />
                </Form.Item>
              </>
            )}
          </Col>
        </Row>
        <Row>
          <Col>
            <Divider style={{ margin: 0 }} />
          </Col>
        </Row>
        <Row className="container" style={{ marginTop: 0, marginBottom: 0 }}>
          <Col span={24}>
            <Typography.Title level={4}>奖励设置</Typography.Title>
          </Col>
          <Col span={24}>
            <Form.Item label="奖励类型">
              <Radio.Group onChange={() => {}} value={1} defaultValue={1}>
                <Radio value={1}>优惠券</Radio>
                <Radio value={2} disabled>
                  积分
                </Radio>
                <Radio value={3} disabled>
                  商品
                </Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item label="活动奖励">
              {/* <Select
                placeholder="请选择"
                value={selectedCoupon}
                onClick={() => setCouponOpen(true)}
                style={{ width: 400 }}
              >
                
                {selectedCoupon && (
                  <Select.Option value={selectedCoupon}>
                    {selectedCoupon}
                  </Select.Option>
                )}
              </Select> */}
              <Button type="primary" onClick={() => setCouponOpen(true)}>
                活动奖励
              </Button>
              <span style={{ marginLeft: 10 }}>{selectedCoupon}</span>
            </Form.Item>
          </Col>
        </Row>
        <Row>
          <Col>
            <Divider style={{ margin: 0 }} />
          </Col>
        </Row>
        <Row className="container" style={{ marginTop: 0, marginBottom: 0 }}>
          <Col span={24}>
            <Typography.Title level={4}>分享设置</Typography.Title>
          </Col>
          <Col span={24}>
            <Form.Item
              label="文章摘要"
              name="shareProfile"
              rules={[
                {
                  required: true,
                  message: '请输入文章摘要',
                  trigger: 'blur'
                }
              ]}
            >
              <Input.TextArea style={{ height: 120, resize: 'none' }} />
            </Form.Item>
            <Form.Item
              label="短链接预览"
              name="shareUrl"
              rules={[
                {
                  required: true,
                  message: '请输入短链接预览',
                  trigger: 'blur'
                }
              ]}
            >
              <Input addonBefore="http://" style={{ width: 300 }} />
            </Form.Item>
            <Form.Item label=" " colon={false}>
              <Button type="primary" htmlType="submit">
                发布
              </Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      {/* 指定店铺 */}
      <Modal
        title="选择店铺"
        open={shopOpen}
        width={750}
        onCancel={() => {
          setShopOpen(false)
          // 判断店铺是否为空
          if (businessId.length === 0) {
            setIsShow(false)
          } else {
            setIsShow(true)
          }
        }}
        // destroyOnClose
        maskClosable={false}
        onOk={() => {
          setShopOpen(false)
          setBusinessId(targetKeys)
          console.log(targetKeys)
          // 通过id找到对应的店铺名称
          const newTargetKeys = targetKeys.map((item) => {
            const target = mockData.find((data) => data.key === item)
            return target ? target.title : ''
          })
          setBusinessName(newTargetKeys)
          // 判断店铺是否为空
          if (businessId.length === 0) {
            setIsShow(false)
          } else {
            setIsShow(true)
          }
        }}
      >
        <Divider />
        <Row>
          <Col span={8} style={{ paddingRight: 20 }}>
            <TreeSelect
              style={{ width: '100%' }}
              placeholder="区域选择"
              treeData={regionData}
              value={region}
              treeCheckable={true}
              onChange={async (value) => {
                setRegion(value)
                console.log(value)
                // 如果数组不为空
                if (value.length !== 0) {
                  // 查询对应的店铺
                  const res = await shopListByCityIdAPI({
                    cityIdList: value,
                    pageNo: 1,
                    pageSize: 100
                  })
                  console.log(res)
                  // 设置数据
                  const arr = res.data.objects.map((item) => {
                    return {
                      key: item.id,
                      title: item.storeName,
                      chosen: false
                    }
                  })
                  console.log(arr)
                  setMockData(arr)
                } else {
                  setMockData([])
                }
              }}
              showCheckedStrategy={TreeSelect.SHOW_PARENT}
            />
          </Col>
          <Col span={16}>
            <Transfer
              dataSource={mockData}
              showSearch
              titles={['店铺', '店铺']}
              targetKeys={targetKeys}
              onChange={(newValue) => {
                setTargetKeys(newValue)
              }}
              render={(item) => item.title}
            />
          </Col>
        </Row>
      </Modal>
      {/* 指定人群 */}
      <Modal
        title="选择人群"
        open={personOpen}
        width={1000}
        onCancel={() => {
          setPersonOpen(false)
          // 判断人群是否为空
          if (selectedConfirmPersonId.length === 0) {
            setIsShow2(false)
          } else {
            setIsShow2(true)
          }
        }}
        maskClosable={false}
        onOk={() => {
          setPersonOpen(false)
          setSelectedConfirmPersonId(selectedPersonId)
          setSelectedConfirmPerson(selectedPerson)
          // 判断人群是否为空
          if (selectedConfirmPersonId.length === 0) {
            setIsShow2(false)
          } else {
            setIsShow2(true)
          }
        }}
      >
        <Divider />
        <Row>
          <Col span={24}>
            <Form onFinish={() => {}} layout="inline">
              <Form.Item name="person" label="人群名称">
                <Input placeholder="请输入人群名称" />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
            </Form>
          </Col>
        </Row>
        <Row style={{ marginTop: 20 }}>
          <Col span={24}>
            <Table
              rowKey="id"
              // 打开模态框框，设置默认选中人群
              selectedRowKeys={selectedPersonId}
              rowSelection={{
                type: 'checkbox',
                // 获取选中的
                onChange: (selectedRowKeys, selectedRows) => {
                  console.log(selectedRowKeys, selectedRows)
                  // 将groupName放到数组中
                  const selectedRowsName = selectedRows.map(
                    (item) => item.groupName
                  )
                  setSelectedPerson(selectedRowsName)
                  setSelectedPersonId(selectedRowKeys)
                }
              }}
              dataSource={personList}
              columns={[
                { key: 'id', title: '序号', dataIndex: 'id' },
                { key: 'groupName', title: '人群名称', dataIndex: 'groupName' },
                { key: 'desc', title: '人群描述', dataIndex: 'desc' },
                {
                  key: 'userNumber',
                  title: '用户数量',
                  dataIndex: 'userNumber'
                }
              ]}
              pagination={{
                pageSize: 5
              }}
            />
          </Col>
        </Row>
      </Modal>
      {/* 选择优惠券 */}
      <Modal
        title="选择优惠券"
        open={couponOpen}
        width={1000}
        onCancel={() => setCouponOpen(false)}
        maskClosable={false}
        onOk={() => {
          setCouponOpen(false)
          setSelectedCouponId(tmpSelectedCouponId)
          setSelectedCoupon(tmpSelectedCoupon)
        }}
      >
        <Divider />
        <Row>
          <Col span={24}>
            <Form onFinish={() => {}} layout="inline">
              <Form.Item name="couponName" label="优惠券名称">
                <Input placeholder="请输入优惠券名称" />
              </Form.Item>
              <Form.Item name="couponName" label="优惠券类型">
                <Select placeholder="请选择优惠券类型" style={{ width: 200 }} />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Form.Item>
            </Form>
          </Col>
        </Row>
        <Row style={{ marginTop: 20 }}>
          <Col span={24}>
            <Table
              rowKey="id"
              // 设置默认选中的
              selectedRowKeys={tmpSelectedCouponId}
              rowSelection={{
                type: 'radio',
                // 获取选中的
                onChange: (selectedRowKeys, selectedRows) => {
                  console.log(selectedRowKeys, selectedRows)
                  setTmpSelectedCoupon(selectedRows[0].couponName)
                  setTmpSelectedCouponId(selectedRowKeys[0])
                }
              }}
              dataSource={couponList}
              columns={[
                { key: 'id', title: '序号', dataIndex: 'id' },
                {
                  key: 'couponName',
                  title: '优惠券名称',
                  dataIndex: 'couponName'
                },
                {
                  key: 'describes',
                  title: '优惠券类型   ',
                  dataIndex: 'describes'
                },
                { key: 'describes', title: '优惠内容', dataIndex: 'describes' },
                { key: 'usageNum', title: '总数量', dataIndex: 'usageNum' }
              ]}
            />
          </Col>
        </Row>
      </Modal>
    </>
  )
}
